package com.milo.coding.jmm.dcl;


/**
 * @Author milo
 * @Date 2021-01-19 21:10:36
 * @Description DoubleCheckLock
 */
public class Singleton {

    /**
     * 查看汇编指令
     * -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -Xcomp
     */
    private volatile static Singleton myinstance;

    // memory = allocate();  1.分配对象内存空间
    // instance(memory);     2.初始化对象
    // instance = memory;    3.设置instance指向刚分配的内存地址，此时instance！=null
    //
    // 重拍后
    // memory=allocate(); 1.分配对象内存空间
    // instance=memory;   3.设置instance指向刚分配的内存地址，此时instance！=null，但是对象还没有初始化完成！
    // instance(memory);  2.初始化对象
    // private static Singleton myinstance;

    /**
     * 双重锁机制保证单例安全
     * @return
     */
    public static Singleton getInstance() {
        if (myinstance == null) {
            synchronized (Singleton.class) {
                if (myinstance == null) {
                    myinstance = new Singleton();
                }
            }
        }
        return myinstance;
    }

    public static void main(String[] args) {
        Singleton.getInstance();
    }
}
